<?php

namespace App\Http\Controllers\api\seckill;

use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\GoodsSeckill;
use App\Models\GoodsSeckillConfig;
use App\Models\Order;
use App\Models\StoreOrder;
use App\Service\CommonService;
use App\Service\EsasticSearch;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Mockery\Exception;

class SeckillController extends Controller
{
    public function getSecketList()
    {
        $h = date('H');
        $h = intval($h);
        $arr = [];
        $dateH = date("Y-m-d H:00:00");
        $seckillGoods = GoodsSeckillConfig::rightJoin('goods_seckill', 'goods_seckill_config.id', '=', 'goods_seckill.config_id')->where('action_time', 'like', '%' . date('Y-m-d') . '%')->get()->toArray();

        foreach ($seckillGoods as $key => $value) {
            for ($i = $h; $i < $h + 4; $i++) {
                if (strtotime($dateH) + ($i - intval(date('H'))) * 3600 < strtotime($value['action_time']) && strtotime($value['action_time']) < strtotime($dateH) + ($i + 1 - intval(date('H'))) * 3600) {
                    $arr['date-h'][$i.":00"][] = $value;
                } else {
                    if (empty($arr['date-h'][$i.":00"])) {
                        $arr['date-h'][$i.":00"] = [];
                    }
                }
            }
        }
        $arr['hot'] = GoodsSeckill::join('goods_seckill_config', 'goods_seckill_config.id', '=', 'goods_seckill.config_id')->where('seckill_status', '=', 1)->get()->toArray();
        return CommonService::success(200, '获取秒杀列表数据', $arr);
    }

    public function SeckillDetail()
    {
        $uid = intval(\request()->get('uid'));//获取用户id
        $seckillId = intval(\request()->get('seckill_id'));//获取商品id
        if (empty($uid) || empty($seckillId)) return CommonService::fail(9999, '传递的参数不能为空');
        if (!Address::where('address_rid', $uid)->where('address_stare', 1)->get()) return CommonService::fail(9999, '请您设置收货地址');
        try {
            $goodsDb = GoodsSeckill::with(['goods', 'config'])->where('id', $seckillId)->get()->toArray();
            return CommonService::success(200, '获取详情页数据', $goodsDb);
        } catch (Exception $e) {
            return CommonService::fail(9999, $e->getMessage());
        }
    }

    public function BegainSeckill()
    {
        $uid = intval(\request()->get('uid'));//获取用户id
        $goodsId = intval(\request()->get('seckill_id'));//获取商品id
        if (empty($uid) || empty($goodsId)) return CommonService::fail(9999, '传递的参数不能为空');
        try {
            $addressDb = Address::where('address_rid', $uid)->where('address_stare', 1)->first();
            if (empty($addressDb)) return CommonService::fail(9999, '请添加选择您的收货地址');
            $addressDb = $addressDb->toArray();
            $seckillGoods = GoodsSeckill::where('goods_id', $goodsId)->first();
            if (!$seckillGoods) return CommonService::fail(9999, '商品不存在');

            $seckillQueue = Redis::lpop('goods_id-' . $goodsId);//先生成订单。再让用户去支付
            if (!$seckillQueue) {
                if (!$seckillQueue) return CommonService::fail(9999, '对不起，此商品已经被抢完了');
            }

            $seckillGoods = $seckillGoods->toArray();
            $seckillOrder = [
                'order_id' => rand(1111, 9999) . time(),
                'uid' => $uid,
                'user_address' => $addressDb['address_name'],
                'cart_id' => 0,
                'freight_price' => 0,
                'total_num' => 1,
                'total_price' => $seckillGoods['seckill_price'],
                'total_postage' => 0,
                'pay_price' => $seckillGoods['seckill_price'],
                'pay_postage' => 0,
                'deduction_price' => 0,
                'coupon_id' => 0,
                'coupon_price' => 0,
                'paid' => 0,
//                'pay_time' => '',
                'pay_type' => '',
                'status' => 0,
                'refund_status' => 0,
                'delivery_name' => $addressDb['address_name'] . '的快递',
                'delivery_type' => 0,
                'mark' => '',
                'combination_id' => 0,
                'pink_id' => 0,
                'seckill_id' => $seckillGoods['id'],//秒杀业务
                'bargain_id' => 0,
                'store_id' => 0,
                'shipping_type' => 1,
                'goods_id' => $goodsId,
                'created_at' => date('Y-m-d H:i:s')
            ];

            $insertId = StoreOrder::insertGetId($seckillOrder);
            if ($insertId) {
                return CommonService::success(200, '您已成功抢到商品，请前往订单页支付',$insertId);
            }

            return CommonService::fail(9999, '系统繁忙');
        } catch (Exception $e) {
            return CommonService::fail(9999, $e->getMessage());
        }
    }

    public function seckillGoodsSearch()
    {
        $searchWord = \request()->get('searchWord');
        if (!$searchWord) return CommonService::fail(9999, '检索的值不能为空');
        $searchData = EsasticSearch::search('seckill',  'activity_title', $searchWord);//索引名称 要搜的字段。搜索的内容
        return CommonService::success(200, $searchData);
    }

}
